import WebApp from '@twa-dev/sdk';
import React, { useCallback, useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next'
import styled from 'styled-components';
import { useDispatch } from 'react-redux';
import { update } from '../../reducer/userReducer';
import { telegramLogin } from '../../service';
import { formatInitData, saveToken, saveUserData } from '../../utils/user';
import { Router } from '../../router';
import gtag from '../../google/analytics';
import Recaptcha from '../../google/recaptcha';
import { fetchSettings } from '../../utils/settings';
import { GtagEvent } from '../../google/analytics/Event';
import Loading from '../../component/Loading';
import Modal from '../../component/Modal';
import Telegram from '../../utils/telegram';
import SwitchConfig from '../../utils/switch';


const Content = styled.div`
    min-height: 100vh;
    background-color: ${(prop) => prop.theme.background.normal};
`

const Error = styled.div`
    color: #FFFFFF;
    font-size: 1.125rem;
    text-align: center;
    white-space:pre-line;
`

const MiniLogin: React.FC = () => {
    const dispatch = useDispatch()
    const navigate = useNavigate()
    const { t } = useTranslation()
    const [spinning, setSpinning] = useState(false);

    const restart = useCallback((msg: string) => {
        if (!msg) {
            return
        }

        Modal.info({
            content: {
                content: <Error>{msg}</Error>
            },
            footer: {
                okText: t('modal.restart'),
                okClick: () => {
                    WebApp.disableClosingConfirmation();
                    WebApp.close()
                    WebApp.openTelegramLink(Telegram.miniApp())
                },
            }
        })
    }, [t])

    const login = useCallback(async (initData: string) => {
        setSpinning(true)
        const result = await telegramLogin({ initData })
        const telegramInfo = formatInitData(initData)
        setSpinning(false)
        const info = result.data
        let id = String(telegramInfo.user?.id);
        if (info) {
            const authDate = telegramInfo.auth_date
            if (authDate) {
                info.authDate = Number(authDate) * 1000;
            }

            id = String(info.id);
            info.token = initData;
            const userInfo = saveUserData(info)
            dispatch(update(userInfo))
        }

        gtag.configUser(id)
        gtag.event(GtagEvent.Login, { success: result.success })

        if (result.success) {
            navigate(Router.Root, { replace: true })
            return
        }

        const message = result.message || t('error.telegramLogin');
        restart(message)

    }, [dispatch, navigate, restart, t])

    const fetchUserInfo = useCallback(async () => {
        let initData: string | undefined = WebApp.initData
        if (!initData) {
            initData = process.env.REACT_APP_TEST_LOGIN_DATA
        }
        if (!initData) {
            restart(t('error.telegramNoData'))
            return
        }
        saveToken(initData);
        setSpinning(true)
        const config = await fetchSettings(true);
        // after login success, need to update config
        SwitchConfig.updateConfig(config)
        const recaptcha = await new Recaptcha().init();
        setSpinning(false)
        if (!recaptcha) {
            login(initData);
            return;
        }
        // check robot
        const id = recaptcha.render((success, reset) => {
            if (!success) {
                reset();
                return;
            }
            login(initData)
        })

        if (id === undefined) {
            login(initData)
        }

    }, [login, restart, t])

    useEffect(() => {
        fetchUserInfo()
    }, [fetchUserInfo])

    return <Content >
        <Loading
            show={spinning}
        />
    </Content>
}

export default MiniLogin